package com.tianmenguide.wxapi;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tianmenguide.common.config.RuoYiConfig;
import com.tianmenguide.common.core.domain.AjaxResult;
import com.tianmenguide.common.utils.DateUtils;
import com.tianmenguide.common.utils.file.FileUploadUtils;
import com.tianmenguide.common.utils.file.FileUtils;
import com.tianmenguide.common.utils.http.HttpUtils;
import com.tianmenguide.framework.config.ServerConfig;
import com.tianmenguide.guide.domain.WxappConfig;
import com.tianmenguide.guide.domain.Wxuser;
import com.tianmenguide.guide.service.IWxappConfigService;
import com.tianmenguide.guide.service.IWxuserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/wxapi/")
@RequiredArgsConstructor
@Api(tags = "小程序登录api")
@Slf4j
public class WxLoginController {

    /**
     * 测试接口
     * @return
     */
    @GetMapping("test")
    public AjaxResult test(){
        log.info("小程序api调试成功");
        return AjaxResult.success("小程序api调试成功！~");
    }

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    private final IWxuserService wxuserService;

    private final IWxappConfigService wxappConfigService;

    private final ServerConfig serverConfig;

    /**
     * 登录时获取的 code（微信官方提供的临时凭证）
     * @param object
     * @return
     */
    @ApiOperation("小程序登录")
    @PostMapping("/wxlogin")
    public AjaxResult wxLogin(@RequestBody JSONObject object){
        WxappConfig wxappConfig = new WxappConfig();
        wxappConfig.setState(0L);
        WxappConfig wxappConfig1 = wxappConfigService.selectWxappConfigList(wxappConfig).get(0);

        String appID = wxappConfig1.getAppid();

        String appSecret = wxappConfig1.getAppSecret();
        //微信官方提供的微信小程序登录授权时使用的URL地址
        String url  = "https://api.weixin.qq.com/sns/jscode2session";
        log.info("信息:{}",object);

        /**
         * 拼接需要的参数
         * appid = AppID 你自己的微信小程序APPID
         * js_code = AppSecret 你自己的微信APP密钥
         * grant_type=authorization_code = code 微信官方提供的临时凭证
         */
        String params = StrUtil.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", appID, appSecret, object.get("code"));
        //开始发起网络请求,若依管理系统自带网络请求工具，直接使用即可
        String res = HttpUtils.sendGet(url,params);
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if (StrUtil.isEmpty(openid)) {
            return AjaxResult.error("未获取到openid");
        }
        /**先通过openid来查询是否存在*/
        Wxuser wxuserToSelect = wxuserService.selectWxuserOpenID(openid);
        if (wxuserToSelect == null){
            /**如果不存在就插入到我们的数据库里*/
            Wxuser wxuser = new Wxuser();
            wxuser.setOpenid(openid);
            wxuser.setCreateTime(DateUtils.getNowDate());
            wxuserService.insertWxuser(wxuser);
            /**返回结果集到前段*/
            return AjaxResult.success(wxuser);
        }else {
            /**返回结果集到前段*/
            return AjaxResult.success(wxuserToSelect);
        }
    }

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {

        try {
            // 指定oss保存文件路径
            String objectName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();
            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());  //注意：这里的值要改为url，前端访问的地址,需要文件的地址 而不是文件名称
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 保存昵称与头像信息到用户信息里
     * @param object
     * @return
     */
    @ApiOperation("保存用户昵称与头像")
    @PostMapping("/saveUserInfo")
    @ResponseBody
    public AjaxResult saveUserInfo(@RequestBody JSONObject object){
        System.out.println(object);
        Wxuser Wxuser = wxuserService.selectWxuserOpenID(String.valueOf(object.get("openid")));
        if (StringUtils.hasLength(String.valueOf(object.get("nickName")))){
            Wxuser.setNickname(String.valueOf(object.get("nickName")));
            Wxuser.setCreateBy(String.valueOf(object.get("nickName")));
        }
        if (StringUtils.hasLength(String.valueOf(object.get("avatarUrl")))){
            Wxuser.setAvatar(String.valueOf(object.get("avatarUrl")));
        }
        Wxuser.setUpdateTime(DateUtils.getNowDate());
        wxuserService.updateWxuser(Wxuser);
        //返回前段需要的数据
        return AjaxResult.success(Wxuser);
    }

}
